<?php

require_once APP . 'controllers/accounts_controller.php';

class TwitterController extends AccountsController {
  var $uses = array('User', 'TwitterAccount');
  
  function login() {
    if (!isset($_REQUEST['oauth_token'])) {
      header('Location: ' . $this->TwitterAuth->request_link());
      exit();
    }
   
    $twitter_account = $this->TwitterAuth->login();
    if (!$twitter_account) {
      $this->setError('Die Anmeldung per Twitter schlug fehl.', 
        array('controller' => 'users', 'action' => 'login'));
    }
   
    $account = $this->TwitterAccount->find('first', array(
      'conditions' => array('TwitterAccount.screen_name' => $twitter_account->screen_name),
      'fields' => array('TwitterAccount.id', 'TwitterAccount.user_id', 'TwitterAccount.screen_name', 'TwitterAccount.oauth_access_token', 'TwitterAccount.oauth_access_token_secret')));

error_log("#0 " . json_encode($twitter_account));
//D error_log("#1 " . json_encode($account));

    $prev_account = $this->Auth->user();
    if ($prev_account) {
      $user_id = $this->User->user_id($prev_account);
      $this->Auth->logout();
    }

    $message = '';
    if ($account) {
      if (isset($user_id) && $user_id && $user_id != $account['TwitterAccount']['user_id']) {
        $this->User->merge_users($user_id, $account['TwitterAccount']['user_id']);
        $message = "Dein Profil {$user_id} wurde in das neue Profil {$account['TwitterAccount']['user_id']} übernommen.\n";
      }
    }
    else {
      if (isset($user_id) && $user_id) {
        // We found a user. Check if we can enhance it with fullname
        $user = $this->User->find('first', array('conditions' => array('id' => $user_id)));
        $data = array();
        if ($twitter_account->name && !$user['User']['name']) {
          $data['name'] = $twitter_account->name;
        }
        if ($data) {
          $this->User->set('id', $user_id);
          $this->User->save($data, /*validate*/FALSE);
        }
      }
      else {
        // No user found. create a new one for this account
        $data = array();
        if ($twitter_account->name) {
          $data['name'] = $twitter_account->name;
        }
        
        if (!$this->User->save($data, /*validate*/FALSE)) {
          error_log("#4 " . json_encode($this->User->validationErrors));
        }
        $user_id = $this->User->getInsertID();
      }
      // We now are sure to have a user id and can create the account
      $data = array(
        'user_id' => $user_id,
        'screen_name' => $twitter_account->screen_name,
        'oauth_access_token' => $twitter_account->oauth_access_token, 
        'oauth_access_token_secret' => $twitter_account->oauth_access_token_secret,
      );
error_log("#5 " . json_encode($data));
      $account = $this->TwitterAccount->save($data);

      if (!$account) {
//D error_log("#2 " . json_encode($this->TwitterAccount->validationErrors));
        $this->setError('Die Anmeldung per Twitter schlug fehl.',
          array('controller' => 'users', 'action' => 'login'));
      }
      else {
        $account['TwitterAccount']['id'] = $this->TwitterAccount->getInsertID();
error_log("#3 " . json_encode($account));
      }
    }

    // Either way, we should now have an $account

    $this->Session->write('auth_component', 'TwitterAuth');
    $this->Session->write('user', $account);        

    if ($account) {
      $this->setSuccess($message . "Du bist erfolgreich per Twitter angemeldet.", 
        array('controller' => 'users', 'action' => 'view', $account['TwitterAccount']['user_id']));
    }
    else {
      $this->setError($message . "Die Anmeldung per Twitter schlug fehl.", 
        array('controller' => 'users', 'action' => 'login'));
    }
  }

  function delete($id) {
    parent::delete($id, 'Twitter');
  }
}
